<template>
    <div class="device-management-container">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>添加设备
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
            <el-dropdown @command="handleColumnToggle">
                <el-button>
                    <el-icon>
                        <Setting />
                    </el-icon>列筛选
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-checkbox-group :model-value="visibleColumns" @update:model-value="visibleColumns = $event">
                            <el-checkbox v-for="column in tableColumns" :key="column.prop" :label="column.prop">
                                {{ column.label }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>

        <!-- 设备表格 -->

        <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column label="Date" width="120">
                <template #default="scope">{{ scope.row.date }}</template>
            </el-table-column>
            <el-table-column fixed prop="equipmentPrimaryKey" label="设备主键" width="150" />
            <el-table-column prop="equipmentName" label="设备名称" width="120" />
            <el-table-column prop="equipmentCode" label="设备编码" width="120" />
            <el-table-column prop="equipmentDescription" label="设备描述" width="120" />
            <el-table-column prop="supplier" label="供应商" width="120" />
            <el-table-column prop="status" label="状态" width="120" />
            <el-table-column prop="creationTime" label="创建时间" width="120" />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-table :data="tableData" style="width: 100%">
        </el-table>

        <!-- 分页组件 -->
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 添加/编辑对话框 -->
        <el-dialog v-model="dialogVisible" title="设备信息" :close-on-click-modal="false">

            <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="设备名称" prop="equipmentName">
                    <el-input v-model="formData.equipmentName" clearable></el-input>
                </el-form-item>
                <el-form-item label="设备编码" prop="equipmentCode">
                    <el-input v-model="formData.equipmentCode" clearable></el-input>
                </el-form-item>
                <el-form-item label="设备描述" prop="equipmentDescription">
                    <el-input v-model="formData.equipmentDescription" type="textarea" :rows="3" clearable></el-input>
                </el-form-item>
                <el-form-item label="供应商" prop="supplier">
                    <el-input v-model="formData.supplier" clearable></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="2">禁用</el-radio>
                        <el-radio :label="3">维修中</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认对话框 -->
        <el-dialog v-model="deleteDialogVisible" title="确认删除" :show-close="false">
            <div>确定要删除选中的设备吗？此操作不可撤销。</div>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确认删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus, Delete, Setting } from '@element-plus/icons-vue';
import http from '@/api/http.js';
import type { TableInstance } from 'element-plus'

interface User {
    id: number
    date: string
    name: string
    address: string
}

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])

const selectable = (row: User) => ![1, 2].includes(row.id)
const toggleSelection = (rows?: User[], ignoreSelectable?: boolean) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(
                row,
                undefined,
                ignoreSelectable
            )
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}

// 设备状态枚举
enum DeviceStatus {
    ENABLED = 1,
    DISABLED = 2,
    REPAIRING = 3
}

// 设备类型定义
interface Device {
    equipmentPrimaryKey: number;
    equipmentName: string;
    equipmentCode: string;
    equipmentDescription: string;
    supplier: string;
    status: number;
    creationTime: string;
}

// 状态文本映射
const statusTextMap = {
    [DeviceStatus.ENABLED]: '启用',
    [DeviceStatus.DISABLED]: '禁用',
    [DeviceStatus.REPAIRING]: '维修中'
};

// 状态标签类型映射
const statusTypeMap = {
    [DeviceStatus.ENABLED]: 'success',
    [DeviceStatus.DISABLED]: 'danger',
    [DeviceStatus.REPAIRING]: 'warning'
};

// 表格数据
const tableData = ref<any>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 列配置
const tableColumns = ref([
    { prop: 'selection', label: '选择', defaultVisible: true },
    { prop: 'equipmentPrimaryKey', label: '设备主键', defaultVisible: true },
    { prop: 'equipmentName', label: '设备名称', defaultVisible: true },
    { prop: 'equipmentCode', label: '设备编码', defaultVisible: true },
    { prop: 'equipmentDescription', label: '设备描述', defaultVisible: true },
    { prop: 'supplier', label: '供应商', defaultVisible: true },
    { prop: 'status', label: '状态', defaultVisible: true },
    { prop: 'creationTime', label: '创建时间', defaultVisible: true },
    { prop: 'operation', label: '操作', defaultVisible: true }
]);

// 可见列控制
const visibleColumns = ref(tableColumns.value
    .filter(col => col.defaultVisible)
    .map(col => col.prop)
);

// 表单数据
const formData = ref<Device>({
    equipmentPrimaryKey: 0,
    equipmentName: '',
    equipmentCode: '',
    equipmentDescription: '',
    supplier: '',
    status: DeviceStatus.ENABLED,
    creationTime: ''
});

// 表单验证规则
const rules = ref<FormRules>({
    equipmentName: [
        { required: true, message: '请输入设备名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    equipmentCode: [
        { required: true, message: '请输入设备编码', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    supplier: [
        { required: true, message: '请输入供应商', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ]
});

// 表单引用
const formRef = ref<FormInstance | null>(null);

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const deleteDialogVisible = ref(false);
const selectedRows = ref<Device[]>([]);
const currentDeleteId = ref<number | number[]>(0);

// 格式化日期
const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString();
};

// 获取设备列表
const getDeviceList = () => {
    loading.value = true;

    // 模拟数据用于测试
    const mockData = {
        data: [
            {
                equipmentPrimaryKey: 1,
                equipmentName: '测试设备1',
                equipmentCode: 'EQ001',
                equipmentDescription: '这是测试设备1的描述',
                supplier: '供应商A',
                status: 1,
                creationTime: '2023-01-01'
            },
            {
                equipmentPrimaryKey: 2,
                equipmentName: '测试设备2',
                equipmentCode: 'EQ002',
                equipmentDescription: '这是测试设备2的描述',
                supplier: '供应商B',
                status: 2,
                creationTime: '2023-02-01'
            },
            {
                equipmentPrimaryKey: 3,
                equipmentName: '测试设备3',
                equipmentCode: 'EQ003',
                equipmentDescription: '这是测试设备3的描述',
                supplier: '供应商C',
                status: 3,
                creationTime: '2023-03-01'
            }
        ],
        totalCount: 3
    };

    // 使用模拟数据
    tableData.value = mockData.data;
    total.value = mockData.totalCount;
    loading.value = false;

    // 注释掉实际API调用，测试完成后可以取消注释
    /*
    http.get('api/EquipmentManagement/EquipmentLedgerQuery/EquipmentLedgerQuery', {
        params: {
            PageIndex: currentPage.value,
            PageSize: pageSize.value
        }
    }).then((res: any) => {
        console.log("获取设备列表", res);
        if (res && res.data) {
            tableData.value = res.data;
            console.log("获取设备列表222", tableData.value);
            total.value = res.totalCount || 0;
        } else {
            tableData.value = [];
            total.value = 0;
            console.error('API返回数据格式不正确', res);
        }
        loading.value = false;
    }).catch((error: any) => {
        console.error('获取设备列表失败:', error);
        ElMessage.error('发生异常' + error.message);
        loading.value = false;
    });
    */
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
    pageSize.value = newSize;
    getDeviceList();
};

// 处理页码变化
const handleCurrentChange = (newPage: number) => {
    currentPage.value = newPage;
    getDeviceList();
};

// 处理选择变化
const handleSelectionChange = (rows: Device[]) => {
    selectedRows.value = rows;
};

// 获取状态文本
const getStatusText = (status: number) => {
    return statusTextMap[status as keyof typeof statusTextMap] || '未知';
};

// 获取状态标签类型
const getStatusType = (status: number) => {
    return statusTypeMap[status as keyof typeof statusTypeMap] || 'info';
};

// 检查列是否可见
const isColumnVisible = (prop: string) => {
    return visibleColumns.value.includes(prop);
};

// 处理列切换
const handleColumnToggle = () => {
    // 无需额外处理，v-model 已绑定
};

// 处理添加
const handleAdd = () => {
    dialogType.value = 'add';
    formData.value = {
        equipmentPrimaryKey: 0,
        equipmentName: '',
        equipmentCode: '',
        equipmentDescription: '',
        supplier: '',
        status: DeviceStatus.ENABLED,
        creationTime: ''
    };
    dialogVisible.value = true;

    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.resetFields();
    });
};

// 处理编辑
const handleEdit = (row: Device) => {
    dialogType.value = 'edit';
    formData.value = { ...row };
    dialogVisible.value = true;

    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.resetFields();
    });
};

// 处理保存
const handleSave = () => {
    formRef.value?.validate((valid) => {
        if (!valid) return;

        const apiUrl = dialogType.value === 'add'
            ? 'api/Management/AddDevice'
            : 'api/Management/UpdateDevice';

        http.post(apiUrl, formData.value)
            .then((res) => {
                if (res.code === 200 || res.code === 300) {
                    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
                    dialogVisible.value = false;
                    getDeviceList();
                } else {
                    ElMessage.warning(`${dialogType.value === 'add' ? '添加失败' : '更新失败'}: ${res.message || '未知错误'}`);
                }
            })
            .catch((error: Error) => {
                console.error(`${dialogType.value === 'add' ? '添加设备' : '更新设备'}失败:`, error);
                ElMessage.error('发生异常,错误信息:' + error);
            });
    });
};

// 处理删除
const handleDelete = (row: Device) => {
    currentDeleteId.value = row.equipmentPrimaryKey;
    deleteDialogVisible.value = true;
};

// 处理批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的设备');
        return;
    }

    currentDeleteId.value = selectedRows.value.map(row => row.equipmentPrimaryKey);
    deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = () => {
    const isBatch = Array.isArray(currentDeleteId.value);
    const apiUrl = isBatch
        ? 'api/Management/BatchDeleteDevice'
        : 'api/Management/DeleteDevice';

    const params = isBatch
        ? { deviceIds: currentDeleteId.value }
        : { deviceId: currentDeleteId.value };

    http.post(apiUrl, params)
        .then((res) => {
            if (res.code === 400) {
                ElMessage.success('删除成功');
                deleteDialogVisible.value = false;
                getDeviceList();
                selectedRows.value = [];
            } else {
                ElMessage.warning(`删除失败: ${res.message || '未知错误'}`);
            }
        })
        .catch((error: Error) => {
            console.error('删除设备失败:', error);
            ElMessage.error('发生异常,错误信息:' + error);
        });
};

// 初始化
onMounted(() => {
    getDeviceList();
});
</script>

<style scoped>
.device-management-container {
    padding: 20px;
    background-color: #fff;
    min-height: 100vh;
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>